'''
@create_time: 2025/10/17 上午11:45
@Author: GeChao
@File: Asn_list_business.py
'''
from playwright.async_api import Page
from page.wms.in_warehouse.Asn_list_page import ASNListPage
from tools.get_case_data import ExtractSubstring
from tools.log import Logger

logger = Logger().logger


def is_valid(value):
    """判断是否需要输入的有效值（排除None和空字符串）"""
    return value not in [None, ""]


class Asn_list_business(ASNListPage):
    """ASN列表业务逻辑层"""

    def __init__(self, page: Page, **kwargs):
        super().__init__(page)

        self.asn_no = kwargs.get('ASN单号')
        self.status = kwargs.get('状态')
        self.is_priority = kwargs.get('是否优先处理')
        self.source_no = kwargs.get('来源单号')
        self.shipper = kwargs.get('货主')
        self.container_no = kwargs.get('柜号')
        self.type_warehousing = kwargs.get('入库类型')
        self.esti_arrival_time = kwargs.get('预计到货时间')
        self.act_arrival_time = kwargs.get('实际到货时间')
        self.listing_start_time = kwargs.get('上架开始时间')
        self.listing_finish_time = kwargs.get('上架完成时间')
        self.delivery_method = kwargs.get('收获方式')
        self.unloading_type = kwargs.get('卸货类型')
        self.service_attr = kwargs.get('业务属性')
        self.sku_all = kwargs.get('SKU')
        self.warehouse_method = kwargs.get('送仓方式')
        self.product_form = kwargs.get('商品形态')
        self.has_or_no_tray = kwargs.get('是否携带托盘')
        self.pack_warehouse_opera = kwargs.get('集货仓作业')
        self.shipping_mark = kwargs.get('箱唛')
        self.has_or_no_out_unload = kwargs.get('是否外包卸货')
        self.unload_company = kwargs.get('卸货公司')

    async def set_up(self):
        """进入ASN列表页面"""
        # 检查"入库"菜单是否已展开
        is_visible = await (await self.click_input(role="menuitem")).text_filter("入库").is_visible()
        if not is_visible:
            # 如果入库菜单不可见，先点击 WMS 菜单展开
            await (await self.click_input(role="menuitem")).text_filter("WMS").click()
        await (await self.click_input(role="menuitem", name="入库")).click()
        await (await self.click_input(role="link", name="ASN列表")).click()

    async def business(self):
        """业务处理 - 搜索并验证ASN单号"""
        await (await self.click_input(role="button", name="展开")).click()
        try:
            # # 输入搜索条件
            if is_valid(self.asn_no):
                await (await self.click_input(role="textbox", name="ASN单号")).fill(self.asn_no)
            if is_valid(self.status):
                await (await self.click_input(role="combobox", name="状态")).click()
                await (await self.text_element(text=self.status)).click()
            if is_valid(self.is_priority):
                await (await self.click_input(role="combobox", name="是否优先处理")).click()
                await (await self.blue_white_dropdown(title=self.is_priority, exact=True)).click()
            if is_valid(self.source_no):
                await (await self.source_no_input).fill(self.source_no)
            # if is_valid(self.shipper):
            #     await (await self.click_input(role="combobox", name="货主")).click()
            #     await (await self.click_input(role="combobox", name="货主")).fill(self.shipper.lower())
            #     await (await self.search_dropdown(text=self.shipper)).click()
            if is_valid(self.container_no):
                await (await self.click_input(role="textbox", name="柜号")).fill(self.container_no)
            if is_valid(self.type_warehousing):
                # 点击入库类型下拉框
                await (await self.click_input(role="combobox", name="入库类型")).click()
                await (await self.text_element(text=self.type_warehousing)).click()
            # if is_valid(self.esti_arrival_time):
            #     await (await self.click_input(role="textbox", name="预计到货时间")).click()
            #     time = ExtractSubstring.extract_substring(self.esti_arrival_time, 4, 6)
            #     await (await self.click_input(role="button", name="10月")).click()
            #     await (await self.text_element(text="9月")).click()
            #     await (await self.title_with_div(title=time)).click()
            #     await (await self.title_with_div(title=time)).click()
            if is_valid(self.delivery_method):
                await (await self.click_input(role="combobox", name="收货方式")).click()
                await (await self.text_element(text=self.delivery_method)).click()
            if is_valid(self.unloading_type):
                await (await self.click_input(role="combobox", name="卸货类型")).click()
                await (await self.text_element(text=self.unloading_type)).click()
            if is_valid(self.service_attr):
                await (await self.click_input(role="combobox", name="业务属性")).click()
                await (await self.blue_white_dropdown(title=self.service_attr)).click()
            if is_valid(self.sku_all):
                sku_code, sku_display = ExtractSubstring.sku_name_parse(self.sku_all)
                await (await self.click_input(role="combobox", name="SKU")).fill(sku_code)
                await (await self.text_element(text=sku_display)).click()
            if is_valid(self.warehouse_method):
                await (await self.click_input(role="combobox", name="送仓方式")).click()
                await (await self.blue_white_dropdown(title=self.warehouse_method)).click()
            if is_valid(self.product_form):
                await (await self.click_input(role="combobox", name="商品形态")).click()
                await (await self.blue_white_dropdown(title=self.product_form)).click()
            if is_valid(self.has_or_no_tray):
                await (await self.click_input(role="combobox", name="是否携带托盘")).click()
                await (await self.blue_white_dropdown(title=self.has_or_no_tray)).nth(2).click()
            if is_valid(self.pack_warehouse_opera):
                await (await self.click_input(role="combobox", name="集货仓作业")).click()
                await (await self.blue_white_dropdown(title=self.pack_warehouse_opera)).nth(2).click()
            # 可以继续添加其他搜索条件...
            if is_valid(self.shipping_mark):
                await (await self.click_input(role="textbox", name="箱唛")).fill(self.shipping_mark)
            if is_valid(self.has_or_no_out_unload):
                await (await self.click_input(role="combobox", name="是否外包卸货")).click()
                await (await self.blue_white_dropdown(title=self.has_or_no_out_unload)).nth(4).click()
            if is_valid(self.unload_company):
                await (await self.click_input(role="combobox", name="卸货公司")).fill(self.unload_company)
                await (await self.title_with_div(title=self.unload_company)).click()

            # 点击搜索按钮 - 静态元素需要先 await 获取元素,再调用方法
            await (await self.search_button).click()
            await self.page.wait_for_timeout(2000)
            # 检查是否有搜索结果
            no_data_element = self.page.locator(".ant-empty-description")  # Ant Design 的空状态元素
            has_no_data = await no_data_element.count() > 0
            if has_no_data:
                # 搜索结果为空，根据预期判断是否失败
                logger.warning("⚠️ 搜索结果为空")
                return False  # 默认认为搜索结果为空就是失败
            # 验证搜索结果 - 只验证填写了的字段
            if is_valid(self.asn_no):
                actual_asn = await (await self.table_cell(row=0, column=2)).text_content()
                assert actual_asn == self.asn_no, f"❌ ASN单号校验失败: 期望{self.asn_no}，实际{actual_asn}"
            if is_valid(self.status):
                actual_status = await (await self.table_cell(row=0, column=3)).text_content()
                assert actual_status in self.status, f"❌ 状态校验失败: 期望含有{self.status}, 实际{actual_status}"
            if is_valid(self.source_no):
                actual_source_no = await (await self.table_cell(row=0, column=4)).text_content()
                assert actual_source_no == self.source_no, f"❌ 来源单号校验失败: 期望{self.source_no}, 实际{actual_source_no}"
            # if is_valid(self.shipper):
            #     actual_shipper = await (await self.table_cell(row=0, column=5)).text_content()
            #     assert actual_shipper == self.shipper, f"❌ 货主校验失败: 期望{self.shipper}, 实际{actual_shipper}"
            if is_valid(self.container_no):
                actual_container_no = await (await self.table_cell(row=0, column=6)).text_content()
                assert actual_container_no == self.container_no, f"❌ 柜号校验失败: 期望{self.container_no}, 实际{actual_container_no}"
            if is_valid(self.type_warehousing):
                actual_type_warehousing = await (await self.table_cell(row=0, column=7)).text_content()
                assert actual_type_warehousing in self.type_warehousing, f"❌ 入库类型校验失败: 期望{self.type_warehousing}, 实际{actual_type_warehousing}"
            if is_valid(self.sku_all):
                pass
            return True
        except AssertionError as e:
            logger.error(e)
            return False
        except Exception as e:
            logger.error(e)
            return False
